package com.syyo.gulimall.seckill.scheduled;

import com.syyo.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: wang
 * @date: 2021/5/20 17:29
 * @Description: 秒杀商品定时上架
 * 每天晚上3点：上架最近三天需要秒杀的商品
 * 当天 00:00:00 - 23:59:59
 * 明天 00:00:00 - 23:59:59
 * 后天 00:00:00 - 23:59:59
 */
@Slf4j
@Component
public class SeckillSkuScheduled {

    @Autowired
    SeckillService seckillService;


    @Autowired
    RedissonClient redissonClient;


    private final String upload_lock = "dseckill:upload:lock";// 分布式秒杀商品上架锁

    /**
     * 幂等性处理
     */
//    @Scheduled(cron = "*/3 * * * * ?")
    @Scheduled(cron = "0 * * * * ?")
    public void uploadSeckillSku() {

        System.out.println("=============上架秒杀===============");
        //1.处理重复上架
        // 使用分布式锁锁住定时任务
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSku();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }


    }
}
